package ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.peng.auctionsystem.MainActivity;
import com.peng.auctionsystem.R;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import Widget.CustomToolBar;
import base.BaseActivity;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import entity.PublicEntity;
import entity.SavePictureEntity;
import entity.UpdateCommodityInfoEntity;
import kr.co.namee.permissiongen.PermissionGen;
import manager.ApiRequestManager;
import manager.RxSchedulers;
import manager.RxSubscriber;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;
import utils.BitmapUtils;
import utils.LogUtils;
import utils.ToastUtil;

/**
 * 发布和编辑竞品界面
 */
public class PublishActivity extends BaseActivity implements CustomToolBar.OnToolBarClickListener {

    private static final String TAG = "PublishActivity";

    private int REQUEST_IMAGE = 1;
    private int REQUEST_CODE_SDCARD = 2;
    private int START_TIME_CODE = 3;
    private int END_TIME_CODE = 4;

    private ArrayList<String> defaultDataArray = new ArrayList<>();


    @Bind(R.id.custom_toolbar)
    CustomToolBar customToolbar;
    @Bind(R.id.publish_iv_pic)
    ImageView publishIvPic;
    @Bind(R.id.publish_btn_getpic)
    Button publishBtnGetpic;
    @Bind(R.id.publish_et_title)
    EditText publishEtTitle;
    @Bind(R.id.publish_tv_start_time)
    TextView publishTvStartTime;
    @Bind(R.id.publish_tv_end_time)
    TextView publishTvEndTime;
    @Bind(R.id.publish_et_price)
    EditText publishEtPrice;
    @Bind(R.id.publish_et_gradient)
    EditText publishEtGradient;
    @Bind(R.id.publish_et_desc)
    EditText publishEtDesc;
    @Bind(R.id.tv_picPath)
    TextView tvPicPath;

    private int flag = 1;// 0-编辑 1-发布
    private String headPortraitPath;
    private String title;
    private String startPrice;
    private String priceGradient;
    private String des;
    private String startTime;
    private String endTime;
    private String localPicPath;
    private int userId;
    private String serverPicPath;
    private int id;

    private String commodityTitle;
    private int auctionGradient;
    private int initialPrice;

    @Override
    public int getLayoutId() {
        return R.layout.activity_publish;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        flag = getIntent().getIntExtra("isPublish", 1);
        id = getIntent().getIntExtra("id", 0);
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        commodityTitle = bundle.getString("commodityTitle");
        startTime = bundle.getString("startTime");
        endTime = bundle.getString("endTime");
        auctionGradient = bundle.getInt("auctionGradient");
        des = bundle.getString("des");
        initialPrice = bundle.getInt("initialPrice");
        initViews();
    }

    private void initViews() {
        customToolbar.findTextView(R.id.left_tv).setVisibility(View.GONE);
        customToolbar.findImageView(R.id.left_iv).setVisibility(View.VISIBLE);
        TextView tv_tight = customToolbar.findTextView(R.id.right_tv_main);
        tv_tight.setVisibility(View.VISIBLE);
        customToolbar.findTextView(R.id.right_tv_sub).setVisibility(View.GONE);
        tv_tight.setText("发布");
        if (flag == 0) {
            customToolbar.findTextView(R.id.center_tv).setText("编辑");
        } else if (flag == 1) {
            customToolbar.findTextView(R.id.center_tv).setText("发布竞品");
        }
        customToolbar.setOnCustomToolBarClickListener(this);

        if (!LogUtils.isEmpty(commodityTitle)){
            publishEtTitle.setText(commodityTitle);
        }
        if (!LogUtils.isEmpty(startTime)){
            publishTvStartTime.setText(startTime);
        }
        if (!LogUtils.isEmpty(endTime)){
            publishTvEndTime.setText(endTime);
        }
        if (!LogUtils.isEmpty(initialPrice + "")){
            publishEtPrice.setText(initialPrice + "");
        }
        if (!LogUtils.isEmpty(auctionGradient + "")){
            publishEtGradient.setText(auctionGradient + "");
        }
        if (!LogUtils.isEmpty(des)){
            publishEtDesc.setText(des);
        }
    }

    @OnClick({R.id.publish_btn_getpic, R.id.publish_tv_start_time, R.id.publish_tv_end_time})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.publish_btn_getpic:// 点击获取图片

                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                    chooseImage();
                } else {
                    if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                            == PackageManager.PERMISSION_GRANTED) {
                        chooseImage();
                    } else {
                        //申请权限
                        PermissionGen.with(this)
                                .addRequestCode(REQUEST_CODE_SDCARD)
                                .permissions(Manifest.permission.READ_EXTERNAL_STORAGE)
                                .request();
                    }
                }

                break;
            case R.id.publish_tv_start_time:// 开始时间
                publishTvStartTime.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(PublishActivity.this, CalendarChooseActivity.class);
                        startActivityForResult(intent, START_TIME_CODE);
                    }
                });
                break;
            case R.id.publish_tv_end_time:// 结束时间

                publishTvEndTime.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(PublishActivity.this, CalendarChooseActivity.class);
                        startActivityForResult(intent, END_TIME_CODE);
                    }
                });

                break;
        }
    }

    private void chooseImage() {
        Intent intent = new Intent(mContext, MultiImageSelectorActivity.class);
        // 是否显示调用相机拍照
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
        // 最大图片选择数量
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 1);
        // 设置模式 (支持 单选/MultiImageSelectorActivity.MODE_SINGLE 或者 多选/MultiImageSelectorActivity.MODE_MULTI)
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
        // 默认选择图片,回填选项(支持String ArrayList)
        intent.putStringArrayListExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, defaultDataArray);
        startActivityForResult(intent, REQUEST_IMAGE);
    }

    @Override
    public void onTitleLeftClick(View view) {
        finish();
    }

    @Override
    public void onTitleCenterClick(View view) {

    }

    @Override
    public void onTitleRightClick(View view) {

        SharedPreferences sPreferences = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        userId = sPreferences.getInt("userId", 0);

        localPicPath = tvPicPath.getText().toString();
        title = publishEtTitle.getText().toString();
        startTime = publishTvStartTime.getText().toString();
        endTime = publishTvEndTime.getText().toString();
        startPrice = publishEtPrice.getText().toString();
        priceGradient = publishEtGradient.getText().toString();
        des = publishEtDesc.getText().toString();

        if (localPicPath == null || localPicPath.equals("")) {
            ToastUtil.showShort("请设置商品图片");
            return;
        }
        if (title == null || title.equals("")) {
            ToastUtil.showShort("请设置商品标题");
            return;
        }
        if (startTime == null || startTime.equals("")) {
            ToastUtil.showShort("请设置商品起拍时间");
            return;
        }
        if (startTime == null || startTime.equals("")) {
            ToastUtil.showShort("请设置商品结束时间");
            return;
        }
        if (endTime == null || endTime.equals("")) {
            ToastUtil.showShort("请设置商品图片");
            return;
        }
        if (startPrice == null || startPrice.equals("")) {
            ToastUtil.showShort("请设置商品起始价格");
            return;
        }
        if (priceGradient == null || priceGradient.equals("")) {
            ToastUtil.showShort("请设置商品竞价梯度");
            return;
        }
        if (des == null || des.equals("")) {
            ToastUtil.showShort("请输入上面简介");
            return;
        }

        uploadingHeadPortrait(localPicPath);

    }

    /**
     * 上传商品图片
     */
    private void uploadingHeadPortrait(String headPortrait) {
        //File file = new File(headPortrait);

        String picPath = headPortrait.substring(headPortrait.length() - 5, headPortrait.length());

        File headFile = BitmapUtils.samplingRateCompress(headPortrait, new File(getSDPath() + "/" + picPath));

        Log.d(TAG, "uploadingHeadPortrait: " + headPortrait);
        if (headFile != null && headFile.exists() && headFile.length() > 0) {
            mRxManager.add(
                    ApiRequestManager.getInstance().uploadFile(headFile)
                            .compose(RxSchedulers.<SavePictureEntity>io_main())
                            .subscribe(new RxSubscriber<SavePictureEntity>(this) {
                                @Override
                                protected void _onNext(SavePictureEntity savePictureEntity) {

                                    // TODO 发布操作
                                    if (flag == 0) {// 编辑保存发布
                                        updateCommodityInfo(id, userId, savePictureEntity.getData(), title, startTime, endTime, startPrice, priceGradient, des);
                                    } else {// 发布新竞品
                                        uploadCommodityInfo(userId, savePictureEntity.getData(), title, startTime, endTime, startPrice, priceGradient, des);
                                    }
                                }

                                @Override
                                protected void _onError(String message) {

                                }
                            })
            );
        } else {
            ToastUtil.showShort("文件不存在！");
        }
    }

    /**
     * 获取SDCard的路径
     *
     * @return
     */
    public String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(android.os.Environment.MEDIA_MOUNTED);//判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();//获取跟目录
        }
        return sdDir.toString();
    }


    /**
     * 上传当前发布上传的信息
     *
     * @param userId
     * @param serverPicPath
     * @param title
     * @param startTime
     * @param endTime
     * @param startPrice
     * @param priceGradient
     * @param des
     */
    public void uploadCommodityInfo(int userId, String serverPicPath, String title, String startTime, String endTime, String startPrice, String priceGradient, String des) {
        mRxManager.add(ApiRequestManager.getInstance().publishCommodity(userId, serverPicPath, title, startTime, endTime, startPrice, priceGradient, des)
                .subscribe(new RxSubscriber<PublicEntity>(this) {
                    @Override
                    protected void _onNext(PublicEntity baseResult) {
                        ToastUtil.showShort("发布成功");
                        startActivity(MainActivity.class);
                        finish();
                    }

                    @Override
                    protected void _onError(String message) {
                        ToastUtil.showShort("登陆失败");
                    }
                }));
    }

    /**
     * 更新商品的信息
     *
     * @param userId
     * @param serverPicPath
     * @param title
     * @param startTime
     * @param endTime
     * @param startPrice
     * @param priceGradient
     * @param des
     */
    public void updateCommodityInfo(int commodityId, int userId, String serverPicPath, String title, String startTime, String endTime, String startPrice, String priceGradient, String des) {
        mRxManager.add(ApiRequestManager.getInstance().updateCommodityInfo(commodityId, userId, serverPicPath, title, startTime, endTime, startPrice, priceGradient, des)
                .subscribe(new RxSubscriber<UpdateCommodityInfoEntity>(this) {
                    @Override
                    protected void _onNext(UpdateCommodityInfoEntity baseResult) {
                        ToastUtil.showShort("发布成功");
                        startActivity(MainActivity.class);
                        finish();
                    }

                    @Override
                    protected void _onError(String message) {
                        ToastUtil.showShort("登陆失败");
                    }
                }));
    }

    @Override
    public void onTitleRightSubClick(View view) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE) {
            // 获取返回的图片列表(存放的是图片路径)
            if (data != null) {
                List<String> path = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                headPortraitPath = path.get(0);
                Log.d("tag", "" + headPortraitPath);
                tvPicPath.setText(headPortraitPath);
            }
        }
        if (requestCode == START_TIME_CODE) {
            if (resultCode == RESULT_CANCELED) {
                Bundle bundle = data.getExtras();
                publishTvStartTime.setText(bundle.getString("year") + "-" + bundle.getString("month") + "-" + bundle.getString("day") + " " + "10:00:00");
            }
        }
        if (requestCode == END_TIME_CODE) {
            if (resultCode == RESULT_CANCELED) {
                Bundle bundle = data.getExtras();
                publishTvEndTime.setText(bundle.getString("year") + "-" + bundle.getString("month") + "-" + bundle.getString("day") + " " + "10:00:00");
            }
        }
    }
}
